package com.hh.demo.mq;

import com.alibaba.fastjson.JSONObject;
import com.hh.demo.domain.MessageEmail;
import com.hh.demo.domain.MessageSms;
import com.hh.demo.dto.MessageSmsDto;
import com.hh.demo.service.IMessageEmailService;
import com.hh.demo.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import static com.hh.demo.constants.MqConstants.COURSE_SMS_TAG;
import static com.hh.demo.constants.MqConstants.COURSE_SMS_TOPIC;

/**
 * @author 黄浩
 * @create 2022-07-25 22:33
 */
@Component
@RocketMQMessageListener(consumerGroup = "service-common-smsmessage-consumer",
        topic = COURSE_SMS_TOPIC,
        selectorExpression = COURSE_SMS_TAG
)
@Slf4j
public class SmsMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Resource
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if(body == null || body.length ==0){
            return;
        }
        String message = new String(body, StandardCharsets.UTF_8);
        MessageSmsDto messageSmsDto = JSONObject.parseObject(message, MessageSmsDto.class);
        saveMessageSms(messageSmsDto);
        log.info("发送消息成功："+messageSmsDto.getContent());
    }

    private void saveMessageSms(MessageSmsDto dto) {
        Date date = new Date();
        dto.getUsers().forEach(user->{
            MessageSms messageSms = new MessageSms();
            BeanUtils.copyProperties(dto,messageSms);
            messageSms.setUserId(user.getId());
            messageSms.setSendTime(date);
            messageSmsService.insert(messageSms);
        });
    }
}
